/*
 * @Author: NJ_1098 xiabaoxin
 * @Date: 2025-02-12 10:43:46
 * @LastEditors: NJ_1098 xiabaoxin
 * @LastEditTime: 2025-02-12 13:25:19
 * @Description: 文件上传工具
 */
const fs = require("fs");
const path = require("path");
const moment = require("moment");
const CommonUtils = require("./common.js");
const { systemError, noSupportFileTypeError } = require("../constant/index.js");

/**
 * 文件上传
 * @param {*} file 文件
 * @param {*} type 支持上传的文件类型
 * @returns
 */
const upload = (file, type) => {
  return new Promise((resolve, reject) => {
    let supportTypeList = [];
    if (type) {
      supportTypeList = type;
    }
    if (supportTypeList.length > 0) {
      if (supportTypeList.indexOf(file.mimetype) === -1) {
        noSupportFileTypeError.msg = `${noSupportFileTypeError.msg}：${file.mimetype}`;
        reject(noSupportFileTypeError);
        return ctx.app.emit("error", noSupportFileTypeError, ctx);
      }
    }
    try {
      // 创建文件流
      const fileReader = fs.createReadStream(file.filepath);
      // 创建存储文件夹
      const dirName = moment().format("YYYYMM");
      const dir = path.resolve(__dirname, "../upload/" + dirName);
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }
      // 创建文件名
      const fileName =
        moment().format("YYYYMMDD") +
        "_" +
        CommonUtils.UUID(8, 62) +
        "." +
        file.originalFilename.split(".").pop();
      // 创建文件存储绝对路径
      const fileResource = `${dir}/${fileName}`;
      const writeStream = fs.createWriteStream(fileResource);
      fileReader.pipe(writeStream);
      resolve(`/${dirName}/${fileName}`);
    } catch (err) {
      reject(err);
      return ctx.app.emit("error", systemError, ctx);
    }
  });
};

module.exports = upload;
